<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>WebSocket 消息中心（用户ID：{{ currentUserId }}）</span>
          <el-tag :type="connectionStatus ? 'success' : 'danger'">
            {{ connectionStatus ? "已连接" : "已断开" }}
          </el-tag>
        </div>
      </template>

      <!-- 消息展示区域 -->
      <div class="message-container">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message-item', msg.direction]"
        >
          <div class="message-meta">
            <span v-if="msg.direction === 'received'">来自 {{ msg.fromUserId }}</span>
            <span v-else>发送至 {{ msg.toUserId }}</span>
            <span class="time">{{ msg.timestamp }}</span>
          </div>
          <div class="message-content">{{ msg.content }}</div>
        </div>
      </div>

      <!-- 消息发送表单 -->
      <el-form
        :model="messageForm"
        label-width="80px"
        @submit.native.prevent="sendMessage"
      >
        <el-form-item label="目标用户">
          <el-input
            v-model="messageForm.toUserId"
            placeholder="请输入接收用户ID"
          />
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :disabled="!connectionStatus"
          >
            发送消息
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { Message as ElMessage } from 'element-ui'

export default {
  data() {
    return {
      currentUserId: '',
      socket: null,
      connectionStatus: false,
      messages: [],
      messageForm: {
        toUserId: '',
        content: ''
      }
    }
  },
  mounted() {
    this.initWebSocket()
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close()
    }
  },
  methods: {
    initWebSocket() {
      const token = getToken()
      if (!token) {
        ElMessage.error('未获取到登录令牌，请先登录')
        return
      }

      try {
        const wsUrl = `ws://localhost:8080/ws/endpoint/${encodeURIComponent(token)}`
        this.socket = new WebSocket(wsUrl)

        // 连接成功
        this.socket.onopen = () => {
          this.connectionStatus = true
          ElMessage.success('WebSocket 连接成功')
          // 从 localStorage 获取用户信息（根据实际业务调整）
          const userInfo = JSON.parse(localStorage.getItem('userInfo'))
          this.currentUserId = userInfo ? userInfo.userId : ''
        }

        // 接收消息
        this.socket.onmessage = (event) => {
          const message = JSON.parse(event.data)
          console.log('Received message:', event.data)
          // const message=event.data
          this.messages.push({
            ...message,
            direction: 'received',
            timestamp: new Date().toLocaleTimeString()
          })
        }

        // 连接关闭
        this.socket.onclose = () => {
          this.connectionStatus = false
          ElMessage.warning('WebSocket 连接已关闭')
        }

        // 错误处理
        this.socket.onerror = (error) => {
          console.error('WebSocket 错误:', error)
          ElMessage.error('连接发生错误')
        }

      } catch (e) {
        console.error('WebSocket 初始化失败:', e)
        ElMessage.error('连接初始化失败')
      }
    },

    sendMessage() {
      if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
        ElMessage.warning('连接未就绪')
        return
      }

      if (!this.messageForm.toUserId || !this.messageForm.content) {
        ElMessage.warning('请填写完整信息')
        return
      }

      const messageData = {
        fromUserId: this.currentUserId,
        toUserId: this.messageForm.toUserId,
        content: this.messageForm.content
      }

      try {
        this.socket.send(JSON.stringify(messageData))
        // 添加到消息列表
        this.messages.push({
          ...messageData,
          direction: 'sent',
          timestamp: new Date().toLocaleTimeString()
        })
        // 清空表单
        this.messageForm.content = ''
      } catch (e) {
        console.error('消息发送失败:', e)
        ElMessage.error('消息发送失败')
      }
    }
  }
}
</script>

<style scoped>
/* 样式部分与 Vue 3 版本完全一致，无需修改 */
.message-container {
  height: 400px;
  margin-bottom: 20px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
}

.message-item {
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  max-width: 80%;
}

.message-item.received {
  background-color: #f5f7fa;
  margin-right: auto;
}

.message-item.sent {
  background-color: #409eff;
  color: white;
  margin-left: auto;
}

.message-meta {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-meta .time {
  margin-left: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
